import java.util.LinkedList;
import java.util.List;


public class Leetcode23 {
    public static void main(String[] args) {
        List<Integer> list = new LinkedList<>();
        list.add(1);
        list.add(2);
        list.add(4);
        ListNode res1 = new ListNode();
        createNode(res1, list);


        List<Integer> list1 = new LinkedList<>();
        list1.add(1);
        list1.add(3);
        list1.add(4);
        ListNode res2 = new ListNode();
        createNode(res2, list1);

        ListNode node = mergeKLists(new ListNode[]{res1, res2});

        System.out.println(node);

    }

    private static ListNode createNode(ListNode node, List<Integer> numbers) {
        if (numbers.isEmpty()) {
            return null;
        }

        node.val = numbers.get(0);
        ListNode next = new ListNode();
        numbers.remove(0);
        node.next = createNode(next, numbers);

        return node;
    }

    public static ListNode mergeKLists(ListNode[] lists) {
        ListNode res = null;
        for (ListNode list : lists) {
            res = mergeTwoLists(res, list);
        }
        return res;
    }

    public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if (list1 == null && list2 == null) {
            return null;
        }

        if (list1 == null) {
            return list2;
        } else if (list2 == null) {
            return list1;
        } else {
            if (list1.val < list2.val) {
                list1.next = mergeTwoLists(list1.next, list2);
                return list1;
            } else {
                list2.next = mergeTwoLists(list1, list2.next);
                return list2;
            }
        }
    }

}

